package com.jhc.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jhc.dto.*;
import com.jhc.entity.BacCollege;
import com.jhc.entity.CmsTeacher;
import com.jhc.entity.CmsUser;
import com.jhc.entity.RedisUserInfo;
import com.jhc.service.IBacCollegeService;
import com.jhc.service.ICmsTeacherService;
import com.jhc.service.RedisService;
import com.jhc.utils.CommonResult;
import com.jhc.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师档案  前端控制器
 * </p>
 *
 * @author zhuzhixu
 */
@RestController
@RequestMapping("/teacher")
@Api(tags = "用户 老师用户接口")
public class CmsTeacherController {

    @Autowired
    private ICmsTeacherService iCmsTeacherService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IBacCollegeService iBacCollegeService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public CommonResult register(@RequestBody @Validated CmsRegister cmsRegister) {
        cmsRegister.setPassword("000000");
        if (iCmsTeacherService.register(cmsRegister)) {
            return CommonResult.success("注册成功");
        }
        return CommonResult.failed("工号已存在");
    }

    @PutMapping("/teacher")
    @ApiOperation("用户更新信息")
    public CommonResult updateTeacherInfo(@RequestBody @Validated CmsTeacherUpdate cmsTeacherUpdate) {
        if (iCmsTeacherService.updateInfo(cmsTeacherUpdate)) {
            return CommonResult.success("更新成功");
        }
        return CommonResult.failed("更新失败");
    }

//    @PostMapping("/login")
//    @ApiOperation("用户登陆")
//    public CommonResult login(@RequestBody @Validated CmsLogin cmsLogin) {
//        RedisUserInfo redisUserInfo = iCmsTeacherService.login(cmsLogin.getNumber(), cmsLogin.getPassword());
//        if (redisUserInfo.getToken() == null) {
//            return CommonResult.validateFailed("账号密码错误");
//        }
//        redisUserInfo.setPermissionList(null);
//        return CommonResult.success(redisUserInfo);
//    }

//    @ApiOperation("用户登出")
//    @DeleteMapping("/logout/{staffNumber}")
//    public CommonResult logout(@PathVariable String staffNumber) {
//        System.out.println("参数:" + staffNumber);
//        redisService.remove(staffNumber);
//        return CommonResult.success("成功");
//    }

//    @ApiOperation("查询用户权限user:permission:get")
//    @GetMapping("/{staffNumber}")
//    @PreAuthorize("hasAuthority('user:permission:get')")
//    public CommonResult getPermission(@PathVariable String staffNumber) {
//        return CommonResult.success(iCmsTeacherService.getPermissionList(staffNumber), "查询成功");
//    }

//    @ApiOperation("更新用户权限user:permission:update")
//    @PutMapping("/add/permission")
//    @PreAuthorize("hasAuthority('user:permission:update')")
//    public CommonResult addPermission(@Validated @RequestBody CmsUserPermissionAdd cmsUserPermissionAdd) {
//        // 去重
//        cmsUserPermissionAdd.setAuthList(cmsUserPermissionAdd.getAuthList().stream().distinct().collect(Collectors.toList()));
//        if (iCmsTeacherService.userAddPermission(cmsUserPermissionAdd)) {
//            return CommonResult.success("添加成功");
//        }
//        return CommonResult.success("添加失败");
//    }

//    @ApiOperation("添加用户角色user:role:add")
//    @PostMapping("/role")
//    @PreAuthorize("hasAuthority('user:role:add')")
//    public CommonResult addRole(@Validated @RequestBody CmsUserRoleAdd cmsUserRoleAdd) {
//        if (iCmsTeacherService.userAddRole(cmsUserRoleAdd)) {
//            return CommonResult.success("添加成功");
//        }
//        return CommonResult.failed("用户不存在或者角色不存在");
//
//    }

//    @ApiOperation("删除用户角色user:role:delete")
//    @DeleteMapping("/role")
//    @PreAuthorize("hasAuthority('user:role:delete')")
//    public CommonResult removeRole(@Validated @RequestBody CmsUserRoleAdd cmsUserRoleAdd) {
//        if (iCmsTeacherService.userRemoveRole(cmsUserRoleAdd)) {
//            return CommonResult.success("删除成功");
//        }
//        return CommonResult.failed("删除失败");
//    }

    @ApiOperation("分页条件过滤查询教师用户数据teacher:search:list")
    @PostMapping("/get/teacherPageData")
    @PreAuthorize("hasAuthority('teacher:search:list')")
    public CommonResult<IPage<CmsTeacherViewDto>> teacherPageData(@RequestBody PageVo<CmsTeacherSearchDto> pageVo) {
        return CommonResult.success(iCmsTeacherService.getTeacherPageData(pageVo));
    }

    @ApiOperation("根据id获取该教师数据")
    @GetMapping("/get/teacherDetail/{id}")
    public CommonResult<CmsTeacherViewDto> getDepartmentDetailById(@PathVariable(value = "id", required = true) Long id) {
        CmsTeacher cmsTeacher = iCmsTeacherService.getById(id);
        if (ObjectUtil.isNotNull(cmsTeacher)) {
            CmsTeacherViewDto cmsTeacherViewDto = new CmsTeacherViewDto();
            BeanUtils.copyProperties(cmsTeacher, cmsTeacherViewDto);
            cmsTeacherViewDto.setCollegeName(iBacCollegeService.getOne(new QueryWrapper<BacCollege>().lambda()
                    .select(BacCollege::getName).eq(BacCollege::getNumber, cmsTeacherViewDto.getCollegeNumber())).getName());
            cmsTeacherViewDto.setDepartmentName(iBacCollegeService.getOne(new QueryWrapper<BacCollege>().lambda()
                    .select(BacCollege::getName).eq(BacCollege::getNumber, cmsTeacherViewDto.getDepartmentNumber())).getName());
            return CommonResult.success(cmsTeacherViewDto);
        }
        return CommonResult.success(null, "查询信息不存在");
    }

//    @ApiOperation("修改老师密码")
//    @PatchMapping("/password")
//    public CommonResult updatePassword(@Validated @RequestBody CmsUpdatePasswordDto cmsUpdatePasswordDto) {
//        if (iCmsTeacherService.getOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber, cmsUpdatePasswordDto.getNumber())) == null) {
//            return CommonResult.failed("用户不存在");
//        }
//        if (iCmsTeacherService.updatePassword(cmsUpdatePasswordDto)) {
//            return CommonResult.success("修改成功，请重新登陆");
//        }
//        return CommonResult.failed("修改失败");
//    }

//    @GetMapping("/teacherListByLikeName/{name}")
//    @ApiOperation("获取模糊查询教师列表")
////    @PreAuthorize("hasAuthority('teacher:get:list')")
//    public CommonResult getTeacherListByLikeName(@PathVariable(name = "name") String name) {
//        if (ObjectUtils.isEmpty(name)) {
//            return CommonResult.success(null);
//        }
//        //构造返回对象
//        List<Map<String, Object>> resultList = new ArrayList<>();
//        iCmsTeacherService.getTeacherListByLikeName(name).stream().forEach(teacher -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("teacherNumber", teacher.getNumber());
//            map.put("teacherName", teacher.getName());
//            resultList.add(map);
//        });
//        return CommonResult.success(resultList);
//    }
}
